package itsm.isperp.module.controller.app;

import java.util.Map;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppCommonSourceRelation;
import itsm.isperp.module.service.app.AppCommonSourceRelationService;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2017-03-08 10:34
 */
@Controller
@RequestMapping("app/commonSourceRelation")
public class AppCommonSourceRelationController extends
    BaseController<AppCommonSourceRelation> {

  @Autowired
  protected AppCommonSourceRelationService appCommonSourceRelationService;

  @Override
  public AppCommonSourceRelationService getService() {
    return this.appCommonSourceRelationService;
  }

  @Override
  public String getPageTitle() {
    return "配置";
  }

  @RequestMapping("saveRelation")
  @ResponseBody
  public String saveRelation(HttpServletRequest req) throws Exception {
    String ids = req.getParameter("ids");
    String sourceId = req.getParameter("sourceId");
    String[] idArr = ids.split(",");
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    for (int i = 0; i < idArr.length; i++) {
      if (StringUtils.isNotBlank(idArr[i])) {
        String sql1 = "delete from app_common_source_relation where source_id='"
            + sourceId + "' and to_id='" + idArr[i] + "'";
        jdbcTemplate.execute(sql1);
        AppCommonSourceRelation newRelation = new AppCommonSourceRelation();
        newRelation.setSourceId(sourceId);
        newRelation.setToId(idArr[i]);
        this.getService().saveOrUpdate(newRelation);
      }
    }
    return "ok";
  }

  @RequestMapping("listDetail")
  @ResponseBody
  @Override
  public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
      HttpServletRequest req) {
    String sourceId=req.getParameter("sourceId");
    request.addFilterRule("source_id", JqGridFilterRuleOp.eq, sourceId);
    return this.getService().findAllDetailByRequest(request).toPage();

  }

}
